package sweet.helper

import org.apache.commons.lang.{ StringUtils }

/** Container for implicit methods */
object StringHelper{
  implicit def string2helper(s: String) = new StringHelper(s)
}

/** Enhancement to Java String */
class StringHelper(val orig: String) {
  
  /** A convinient String.format wrapper, but for String instance instead. 
   * This also takes scala varargs and do the autoboxing to java array for you. */
  def fmt(params: Any*) = String.format(orig, 
    params.asInstanceOf[scala.runtime.BoxedObjectArray].
    unbox(params.getClass).asInstanceOf[Array[Object]])
  
  /** Provide a faster split than the {@ String#split}, which uses regex and it's slow!
   * 
   * The implementation is just a wrapper to the Apache's commons-lang StringUtils class.
   * Note that StringUtils.split will split by SINGLE CHAR as Separator, not word!
   * Examples: <pre>
   * scala> import sweet.helper.StringHelper._
   * scala> "/test".fastSplit("/")
   * res0: Array[java.lang.String] = Array(test)
   * scala> "/test/".fastSplit("/")
   * res1: Array[java.lang.String] = Array(test)
   * scala> "/test/foo/bar".fastSplit("/")
   * res3: Array[java.lang.String] = Array(test, foo, bar)
   * scala> "test/foo/bar".fastSplit("/")  
   * res5: Array[java.lang.String] = Array(test, foo, bar)
   * </pre>
   */
  def fastSplit(charSep: String) = StringUtils.split(orig, charSep) 
  
  /** Provide a faster replaceAll method.*/
  def fastReplace(from: String, to: String) = StringUtils.replace(orig, from, to)
  
  override def toString = orig
}

/** Provide names format such as camelCase, packageName, className etc. */
object NamesHelper {   
  import StringHelper.string2helper // implicit string enhancer
  
  def packageName(s: String): String = {
    var res = s
    res = res.fastReplace("-", "") //remove all -      
    res = res.fastReplace("_", "") //remove all _  
    res = res.toLowerCase //low case all letters    
    res
  }
  
  def camelCaseName(s: String): String = {
    var res = new StringBuilder(s)
    var pos = -1
    
    res.replace(0, 1, res.substring(0,1).toUpperCase) // cap first letter.
    
    //remove all - and next char to upper case
    while({ pos = res.indexOf("-"); pos>=0 })
      res.replace(pos, pos+2, res.substring(pos+1, pos+2).toUpperCase)
    
    //remove all _ and next char to upper case
    while({ pos = res.indexOf("_"); pos>=0 })
      res.replace(pos, pos+2, res.substring(pos+1, pos+2).toUpperCase)
    
    res.toString
  }  
}

